<?php

class NotasController extends RController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'rights', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionNotasClase($id){
		$clase = Clase::model()->with(array(
		'curso',
		'curso.periodo',
		'curso.alumnos',
		'evaluaciones',
		'evaluaciones.notas',
		'evaluaciones.notas.alumno',
		'curso.alumnos.user'=>array('order'=>'apellido_paterno ASC'),
		))->findByPk($id);
		$profesor = User::model()->findByPk(Yii::app()->user->id)->profesor;
		$pertenece = false;
		if(!$profesor==null){
			if(isset($clase) && $clase->profesor_idprofesor == $profesor->idprofesor)
				$pertenece=true;
		}
		if(!$clase==null){
			$this->render('NotasClase',array('clase'=>$clase,'pertenece'=>$pertenece,'profesor'=>$profesor));
		}else{
			throw new CHttpException(404,'La página solicitada no existe.');
		}
	}
	
	public function actionCreate($id)
	{
		$model =new Nota;
		$notas[]=new Nota;
		$validar = true;
		$evaluacion = Evaluacion::model()->with(array(
		'clase',
		'clase.curso.alumnos',
		'clase.curso.alumnos.user'=>array('order'=>'apellido_paterno ASC'),
		))->findByPk($id);
		if(isset($evaluacion->clase->curso->alumnos)){
			foreach($evaluacion->clase->curso->alumnos as $i=>$alumno){
				$notas[$i]=new Nota;
				if(isset($evaluacion->notas)){
					foreach($evaluacion->notas as $nota){
						if($alumno->idalumno==$nota->alumno_idalumno && $nota->evaluacion->idevaluacion == $evaluacion->idevaluacion){
							$notas[$i]=Nota::model()->findByPk($nota->idnota);
						}
					}
				}
				
			}
		}
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Nota']))
		{
			foreach($evaluacion->clase->curso->alumnos as $i=>$alumno){
				$notas[$i]->attributes=$_POST['Nota'][$i];
				
				if($notas[$i]->nota<1 || $notas[$i]->nota>7){
					Yii::app()->user->setFlash('notice', "Las notas deben estar entre 1.00 y 7.00");
					print_r($notas[$i]->nota);
				}
				$validar = $notas[$i]->validate() && $validar;
			}
			if($validar){
				foreach($notas as $i=>$nota){
					$notas[$i]->save(false);
				}
				Yii::app()->user->setFlash('success', "Información Enviada con éxito");
				$this->redirect(array('NotasClase','id'=>$evaluacion->clase_idclase));
			}
			else
				Yii::app()->user->setFlash('error', "Formulario no válido!");
			
		}

		$this->render('create',array(
			'model'=>$model,
			'evaluacion'=>$evaluacion,
			'notas'=>$notas
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Nota');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Nota('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Nota']))
			$model->attributes=$_GET['Nota'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Nota::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'La página solicitada no existe.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='nota-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	

}
